package com.toman.ui.work.device;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.PlanEntity;
import com.toman.R;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.camera.Camera;
import com.toman.toolbar.ToolBarActivity;
import com.toman.ui.work.workshop.PlanActivity;
import com.toman.ui.work.workshop.PlanDispatchingActivity;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.toman.Util.DensityUtil.dip2px;

public class DeviceRepairAddActivity extends ToolBarActivity {
    ItemListAdapter adapter, adapter2;
    List<ItemListBean> list = new ArrayList<ItemListBean>();
    List<ItemListBean> listSelect = new ArrayList<ItemListBean>();

    @BindView(R.id.tv_device)
    TextView tvDevice;
    @BindView(R.id.rl_device)
    RelativeLayout rlDevice;
    @BindView(R.id.tv_problem)
    TextView tvProblem;
    @BindView(R.id.rl_problem)
    RelativeLayout rlProblem;
    @BindView(R.id.tv_remark_name)
    TextView tvRemarkName;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_problem_detail)
    TextView tvProblemDetail;
    @BindView(R.id.et_problem_detail)
    EditText etProblemDetail;
    @BindView(R.id.ll)
    LinearLayout ll;
    Camera camera;
    String deviceID = "";
    String problemItemId = "";
    ListView lvSelect;
    Dialog dialog;
    @BindView(R.id.tv_item_name)
    TextView tvItemName;

    @BindView(R.id.rl_item)
    RelativeLayout rlItem;
    @BindView(R.id.rv_item)
    RecyclerView rvItem;
    CommonAdapter<String> adapterItem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_repair_add);
        ButterKnife.bind(this);
        initView();
        initHandler();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
baseEnum=BaseEnum.REPAIR;
        initToolBar(baseEnum.add());
        if (getIntent().getStringExtra("status").equals("1")) {
            ViewUtil.done(tvDevice);

            tvDevice.setText(getIntent().getStringExtra("deviceName"));
            deviceID = getIntent().getStringExtra("deviceId");
//               etItem.setText(getIntent().getStringExtra("problemName"));

initAdapter(Arrays.asList(getIntent().getStringExtra("problemName").split("、")));
            rlItem.setVisibility(View.VISIBLE);
            initToolBar("关联故障项目");
        }
        if (getIntent().getStringExtra("status").equals("2")) {
            tvDevice.setText(getIntent().getStringExtra("deviceName"));
            deviceID = getIntent().getStringExtra("deviceId");
        }
        createPhoto("故障图片");
        adapter = new ItemListAdapter(this);
        adapter2 = new ItemListAdapter(this, 2);
    }

    private void createPhoto(String title) {
        int margin = dip2px(this, 10);
        int etWidth = dip2px(this, 300);
        int h = dip2px(this, 1);
        RelativeLayout rl = new RelativeLayout(this);
        TextView tv1 = new TextView(this);
        tv1.setText(title);
        tv1.setId(R.id.tv_code_title);
        GridLayout gl_camara = new GridLayout(this);
        camera = new Camera(this, gl_camara, false, 9, mHandler, title);
//        camera.showInternet(null);
        gl_camara.requestDisallowInterceptTouchEvent(true);
        tv1.setPadding(margin, margin, margin, margin);
        gl_camara.setPadding(2 * margin, margin, margin, margin);
        ll.addView(tv1);
        ll.addView(gl_camara);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera.onActivityResult(requestCode, resultCode, data);
    }

    public void deviceDialog() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        ListView lv = (ListView) textEntryView.findViewById(R.id.lv);
        lv.setAdapter(adapter);

        builder                //对话框的标题
                .setTitle("选择设备")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        //获取用户输入的“用户名”，“密码”


                    }
                })
                //对话框的“退出”单击事件
//                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        device();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                ItemListBean bean = adapter.getItem(i);
                deviceID = bean.getID();
                tvDevice.setText(bean.getName());
                dialog.dismiss();
            }
        });

    }
    private void initAdapter(List<String> problemNames) {

        GridLayoutManager mgr = new GridLayoutManager(this, 4);

        rvItem.setLayoutManager(mgr);
        adapterItem = new CommonAdapter<String>(this, R.layout.item_tally_problem_item, problemNames) {
            @Override
            protected void convert(ViewHolder holder, String item, final int position) {
Button button=holder.getView(R.id.btn_item);
button.setText(item);




//                权限管理

            }


        };
        rvItem.setAdapter(adapterItem);
    }

    public void device() {


        OkHttpUtils
                .get(NewBaseUrl.device_list_get)
                .params("departmentId", departmentId)
                .params("token", token)
                .params("key", "")
                .params("limit", "1000")
                .params("page", "1")
                .params("moduleName","repair")
                .params("filterByOperate", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "设备列表: " + result);

                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        list.clear();
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("deviceName"), jsonArray.getJSONObject(i).getString("id"));
                                list.add(bean);
                            }
                            if (list.size() == 0) {
                                ToastUtil.makeText(getApplicationContext(), "暂无数据");
                            }
                            adapter.refreshData(list);

                            adapter.notifyDataSetChanged();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    public void problemDialog() {
        final AlertDialog dialog;
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater factory = LayoutInflater.from(this);
        //把activity_login中的控件定义在View中
        final View textEntryView = factory.inflate(R.layout.dialog_list, null);
        lvSelect = (ListView) textEntryView.findViewById(R.id.lv);
        TextView textView = (TextView) textEntryView.findViewById(R.id.tv_nodata);

        lvSelect.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
        lvSelect.setAdapter(adapter2);

        builder                //对话框的标题
                .setTitle("选择故障项目")
                //设定显示的View
                .setView(textEntryView)
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        SparseBooleanArray array;
                        array = lvSelect.getCheckedItemPositions();
                        StringBuilder names = new StringBuilder();
                        StringBuilder ids = new StringBuilder();
                        for (int i = 0; i < array.size(); i++) {
                            if (array.get(i)) {
                                if (names.length() <= 0) {
                                    names.append(listSelect.get(i).getName());
                                    ids.append(listSelect.get(i).getID());
                                } else {
                                    names.append("、").append(listSelect.get(i).getName());
                                    ids.append(",").append(listSelect.get(i).getID());

                                }
                            }
                        }
                        tvProblem.setText(names.toString());
                        problemItemId = ids.toString();

                    }
                })
                //对话框的“退出”单击事件
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create();
        dialog = builder.show();
        getProblemItems(textView);
    }


    public void add() {
        if (deviceID.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择设备");
            return;
        }
        if (problemItemId.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择故障项目");
            return;
        }
        if (etProblemDetail.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请输入故障详细信息");
            return;
        }
        List<String> list = camera.getCompressUrl();
        Map<String, String> map = new HashMap<String, String>();
        map.put("departmentId", departmentId);
        map.put("deviceId", deviceID);
        map.put("remark", etRemark.getText().toString());
        map.put("errorDetail", etProblemDetail.getText().toString());
        map.put("problemItemIds", problemItemId);
        map.put("token", token);
        dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");
        upload((HashMap<String, String>) map, list);
    }
//


    public void getProblemItems(TextView textView) {

        OkHttpUtils
                .get(NewBaseUrl.problemitem_list_get)
                .params("token", token)
                .params("companyId", companyId)
                .params("departmentId", departmentId)
                .params("limit", "1000")
                .params("page", "1")
                .params("status","0")
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "获取故障项目列表: " + result);
                        listSelect.clear();
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");
                            JSONArray jsonArray = Jpage.getJSONArray("list");
                            for (int i = 0; i < jsonArray.size(); i++) {
                                ItemListBean bean = new ItemListBean(jsonArray.getJSONObject(i).getString("itemName"), jsonArray.getJSONObject(i).getString("id"));
                                listSelect.add(bean);
                                lvSelect.setItemChecked(i, false);

                            }
                            if (listSelect.size() == 0) {
                                textView.setVisibility(View.VISIBLE);
//                                ToastUtil.makeText(getApplicationContext(), "暂无数据，请联系管理员！");
                            }
                            else {
                                textView.setVisibility(View.GONE);
                            }
                            adapter2.refreshData(listSelect);
                            adapter2.notifyDataSetChanged();
                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    @OnClick({R.id.tv_device, R.id.tv_problem})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_device:
//                deviceDialog();
                DialogUtils.showDialog(this, NetworkEnum.DEVICE, mCompanyId,new HashMap<String, String>(){{put("departmentId",departmentId);}}, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        deviceID = bean1.getID();
                        tvDevice.setText(bean1.getName());
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.tv_problem:
                problemDialog();
                break;
        }
    }

    private void upload(HashMap<String, String> map, List<String> paths) {
        final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS).build();
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);

//遍历map中所有参数到builder
        for (String key : map.keySet()) {
            mbody.addFormDataPart(key, map.get(key));
        }


        for (String path : paths) {
            File file = new File(path);
            if (file.exists()) {
                mbody.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
            // builder.addFormDataPart("file[]", null, RequestBody.create(MEDIA_TYPE_PNG, new File(path)));
        }


        //构建请求体
        RequestBody requestBody = mbody.build();
        final Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "...")

                .url(NewBaseUrl.devicerepairrecord_save)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                dialog.dismiss();

                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();

                Log.i("新增报修", result);
                JSONObject jsonObj = JSON.parseObject(result);
                int code = jsonObj.getInteger("code");
                ViewUtil.lagout(code, getApplicationContext());
                if (code == 0) {
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                } else {
                    ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                }
            }
        });


    }

    public void add2() {
        if (deviceID.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择设备");
            return;
        }
        if (problemItemId.equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请选择故障项目");
            return;
        }
        if (etProblemDetail.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请输入故障详细信息");
            return;
        }
        dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");

        List<String> list = camera.getCompressUrl();
        List<File> files = new ArrayList<>();
        for (String path : list) {
            File file = new File(path);
            files.add(file);
        }
        OkHttpUtils
                .post(NewBaseUrl.devicerepairrecord_save)
                .headers("token", token)
                .headers("Content-Type", "multipart/form-data")
                .addFileParams("file", files)
                .params("departmentId", departmentId)
                .params("deviceId", deviceID)
                .params("remark", etRemark.getText().toString())
                .params("errorDetail", etProblemDetail.getText().toString())
                .params("problemItemIds", problemItemId)
                .execute(new StringCallback() {
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                        Toast.makeText(getApplicationContext(), "请检查您的网络连接!", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }


                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", getClass().toString() + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            dialog.dismiss();

                            finish();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }
                        dialog.dismiss();

                    }
                });

    }

    private void initHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:
                        dialog.dismiss();
                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);
                        finish();
                        break;
                    case 2:
                        dialog.dismiss();
                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);

                        break;
                    default:
                        break;
                }
            }
        };
    }
}
